import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  /**
   * 向子域发送消息
   * @param msgType
   * @param data
   */
  let postSubDomainMessage = function (msgType, data) {
    try {
      let openDataContext = wx.getOpenDataContext();
      openDataContext.postMessage({
        msgType,
        data: JSON.stringify(data),
      });
    } catch (e) {
      console.error(e);
    }
  };
  
  /**
   * 报告分数
   * @param opts
   */
  let reportScores = function (opts) {
    let reportData = opts.reportData;
    if (!reportData) {
      if (opts.fail) {
        opts.fail({
          errMsg: '无效报告数据'
        });
      }
    }
    let dataList = [];
    let keys = Object.keys(reportData);
    for (let i = 0; i < keys.length; i++) {
      let key = keys[i];
      let value = reportData[key].toString();
      dataList.push({
        key: key,
        value: value
      });
    }
    if (dataList.length === 0) {
      if (opts.success) {
        opts.success(dataList);
      }
      return;
    }
    wx.setUserCloudStorage({
      KVDataList: dataList,
      success: (res) => {
        if (opts.success) {
          opts.success(res);
        }
      },
      fail: (res) => {
        if (opts.fail) {
          opts.fail(res);
        }
      }
    });
  };
  
  module.exports = {
    postSubDomainMessage,
    reportScores,
  }
}